<!-- 批量售后  批量选择商品-->
<template>
  <view :style="mix_diyStyle" style="padding: 20rpx;">
	  <view class="batchSel" >
		<!-- 批量选择需要售后的商品 start -->
		<view class="batch_sel_list" v-if="batchGoodsList.length > 0">
		  <view class="batch_sel_pre sel_list_tag" v-for="(item, index) in batchGoodsList" :key="index">
			<text class="iconfont" :class="{iconziyuan33:item.sel,iconziyuan43:!item.sel}" @click="selGoods(item.productId)"></text>
			<view class="flex_row_start_center right_con">
				<view class="default_goods_image">
				  <image :src="item.productImage" mode="aspectFit"></image>
				</view>
				<view class="default_goods_des">
				  <view class="default_goods_name">{{ item.goodsName }}</view>
				  <view class="default_goods_spec" v-if="item.specValues">{{
					item.specValues
				  }}</view>
				  <view class="default_goods_bottom">
					<view class="default_goods_price" v-if="item.moneyAmount &&
						$getPartNumber(item.moneyAmount, 'int') &&
						$getPartNumber(item.moneyAmount, 'decimal')
						">
					  <text class="unit">{{ $L('¥') }}</text>
					  <text class="price_int">{{
						$getPartNumber(item.moneyAmount, 'int')
					  }}</text>
					  <text class="price_decimal">{{
						$getPartNumber(item.moneyAmount, 'decimal')
					  }}</text>
					</view>
					<view class="default_goods_num">
					  <view class="default_goods_number" v-if="item.afsButton>100">
						<text @click="
						editNum(
						  'reduce',
						  'batch',
						  item.productNum,
						  item.productId,
						  item.currNum
						)
						  ">-</text>
						<input type="text" v-model="item.currNum" @input="
						  editNum(
							'edit',
							'batch',
							item.productNum,
							item.productId,
							item.currNum,
							$event
						  )
						  " class="pre_num" />
						<text @click="
						  editNum(
							'add',
							'batch',
							item.productNum,
							item.productId,
							item.currNum
						  )
						  ">+</text>
					  </view>
					  
					   <text class="num_unedit" v-else>x{{item.currNum}}</text>
					  
					</view>
				  </view>
				</view>
			</view>
			
		  </view>
		</view>
		<!-- 批量选择需要售后的商品 end -->

		<view class="batch_bottom">
		  <text class="submit_btn" @click="goApplyBatch">{{ $L('提交') }}</text>
		</view>
	  </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import recommendGoods from '@/components/recommend-goods.vue'
import uniPopup from '@/components/uni-popup/uni-popup.vue'
import uniPopupMessage from '@/components/uni-popup/uni-popup-message.vue'
import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue'
let startY = 0,
  moveY = 0,
  pageAtTop = true
export default {
  components: {
    recommendGoods,
    uniPopup,
    uniPopupMessage,
    uniPopupDialog
  },
  data() {
    return {
      imgUrl: getApp().globalData.imgUrl,
      coverTransform: 'translateY(0px)',
      coverTransition: '0s',
      moving: false,
      orderSn: '', //订单号
      orderProductId: '', //商品的订单id
      batchList: [], //订单列表
      defaultGoods: {}, //默认商品
      batchGoodsList: [], //同订单的其他商品
      batchSelListAmount: 0, //批量选择的退款总金额
      isEdit: 'true', //数量是否可编辑 默认为可编辑
      batchGoods: [] //当前页面数据的各种信息状态
    }
  },
  onLoad() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: this.$L('售后商品选择')
      })
    }, 0);

    this.orderSn = this.$Route.query.orderSn
    this.orderProductId = this.$Route.query.orderProductId
    this.afsState = this.$Route.query.afsState
    this.batchGoods = JSON.parse(this.$Route.query.batchGoods)
    //订单id
    this.initData()
    this.getOrderDetail()
  },
  // #ifndef MP
  onNavigationBarButtonTap(e) {
    const index = e.index
    if (index === 0) {
      this.navTo('/pages/set/set')
    } else if (index === 1) {
      // #ifdef APP-PLUS
      const pages = getCurrentPages()
      const page = pages[pages.length - 1]
      const currentWebview = page.$getAppWebview()
      currentWebview.hideTitleNViewButtonRedDot({
        index
      })
      // #endif
      this.$Router.push('/pages/notice/notice')
    }
  },
  // #endif
  computed: {
    ...mapState(['hasLogin', 'userInfo', 'userCenterData'])
  },
  methods: {
    initData() { },

    /**
     * 统一跳转接口,拦截未登录路由
     * navigator标签现在默认没有转场动画，所以用view
     */
    navTo(url) {
      if (!this.hasLogin) {
        let urls = this.$Route.path
        const query = this.$Route.query
        uni.setStorageSync('fromurl', {
          url: urls,
          query
        })
        url = '/pages/public/login'
      }
      this.$Router.push(url)
    },

    
    //获取售后商品选择的商品数据
    getOrderDetail() {
      let param = {}
      param.url = 'v3/business/front/after/sale/apply/getOrderProductList'
      param.method = 'GET'
      param.data = {}
      param.data.orderSn = this.orderSn //订单号
      param.data.orderProductId = this.orderProductId
      this.$request(param)
        .then((res) => {
          if (res.state == 200) {
            let result = res.data.filter(ba => ba.afsButton == this.afsState);
            if (this.batchGoods && this.batchGoods.length > 0) {
              this.batchList = result
              this.batchList.map((item) => {
                this.batchGoods.map((item1) => {
                  if (item.orderProductId == item1.orderProductId) {
                    item.currNum = item1.currNum
                    item.sel = item1.sel
                  }
                })
              })
              // 主商品
              this.defaultGoods = this.batchList[0]
              // 同订单的其他商品
              this.batchList.splice(0, 1)
              this.batchGoodsList = this.batchList
            } else {
              this.batchList = result
              // 主商品
              this.defaultGoods = this.batchList[0]
              this.defaultGoods.currNum = this.batchList[0].productNum
              this.defaultGoods.sel = true //sel是否选中
              // 同订单的其他商品
              this.batchList.splice(0, 1)
              this.batchGoodsList = this.batchList
              this.batchGoodsList.map((item, index) => {
                item.currNum = item.productNum
                item.sel = false
              })
            }
          } else {
            this.$api.msg(res.msg)
          }
        })
        .catch((e) => {
          //异常处理
        })
    },
    /**
     * 功能：商品数量的编辑
     * 参数：
     * type:加减编辑
     * sourseType:点击来源 ：default主商品	 batch:同订单的其他商品
     * productNum：该商品数量可编辑的最大值
     * productId:  货品id
     * currNum: 当前商品的数量值
     * e:事件对象	$event
     *
     * */
    editNum(type, sourseType, productNum, productId, currNum, e) {
      let that = this
      if (that.isEdit == 'true') {
        if (sourseType == 'default') {
          //主商品
          if (type == 'add') {
            if (currNum < productNum) {
              that.defaultGoods.currNum++
            } else {
              uni.showToast({
                title: that.$L('不能超出最大限制'),
                duration: 500,
                icon: 'none'
              })
              setTimeout(function () {
                that.defaultGoods.currNum = productNum
              }, 700)
            }
          } else if (type == 'reduce') {
            if (that.defaultGoods.currNum <= 1) {
              uni.showToast({
                title: that.$L('不能低于最小限制'),
                duration: 500,
                icon: 'none'
              })
              setTimeout(function () {
                that.defaultGoods.currNum = 1
              }, 700)
            } else {
              that.defaultGoods.currNum--
            }
          } else if (type == 'edit') {
            that.defaultGoods.currNum = e.detail.value
            if (that.defaultGoods.currNum <= 1) {
              uni.showToast({
                title: that.$L('不能低于最小限制'),
                duration: 500,
                icon: 'none'
              })
              setTimeout(function () {
                that.defaultGoods.currNum = 1
              }, 700)
            } else if (that.defaultGoods.currNum >= productNum) {
              uni.showToast({
                title: that.$L('不能超出最大限制'),
                duration: 500,
                icon: 'none'
              })
              setTimeout(function () {
                that.defaultGoods.currNum = productNum
              }, 700)
            }
          }
          that.$forceUpdate()
        } else if (sourseType == 'batch') {
          //同订单的其他商品
          if (type == 'add') {
            if (currNum < productNum) {
              that.batchGoodsList.map((item, index) => {
                if (item.productId == productId) {
                  item.currNum++
                }
              })
            } else {
              that.batchGoodsList.map((item, index) => {
                if (item.productId == productId) {
                  uni.showToast({
                    title: that.$L('不能超出最大限制'),
                    duration: 500,
                    icon: 'none'
                  })
                  setTimeout(function () {
                    item.currNum = productNum
                  }, 700)
                }
              })
            }
          } else if (type == 'reduce') {
            that.batchGoodsList.map((item, index) => {
              if (item.productId == productId) {
                if (item.currNum <= 1) {
                  uni.showToast({
                    title: that.$L('不能低于最小限制'),
                    duration: 500,
                    icon: 'none'
                  })
                  setTimeout(function () {
                    item.currNum = 1
                  }, 700)
                } else {
                  item.currNum--
                }
              }
            })
          } else if (type == 'edit') {
            that.batchGoodsList.map((item, index) => {
              if (item.productId == productId) {
                item.currNum = e.detail.value
                if (item.currNum <= 1) {
                  uni.showToast({
                    title: that.$L('不能低于最小限制'),
                    duration: 500,
                    icon: 'none'
                  })
                  setTimeout(function () {
                    item.currNum = 1
                  }, 700)
                  item.currNum = 1
                } else if (item.currNum >= productNum) {
                  uni.showToast({
                    title: that.$L('不能超出最大限制'),
                    duration: 500,
                    icon: 'none'
                  })
                  setTimeout(function () {
                    item.currNum = productNum
                  }, 700)
                }
              }
            })
          }
          that.$forceUpdate()
        }
      } else {
        uni.showToast({
          title: that.$L('不可修改'),
          icon: 'none',
          duration: 700
        })
      }
    },
    //商品选中状态的修改
    selGoods(productId) {
      let that = this
      that.batchGoodsList.map((item, index) => {
        if (item.productId == productId) {
          item.sel = !item.sel
        }
      })
      that.$forceUpdate() //强制刷新
    },
    /**
     * 功能：不四舍不入，保留两位小数
     * toFixeds(num,decimal)
     * @param {Object} num   数字（价格）
     * @param {Object} decimal  保留的位数
     */
    toFixeds(num, decimal) {
      num = num.toString()
      let index = num.indexOf('.')
      if (index != -1) {
        num = num.substring(0, decimal + index + 1)
      } else {
        num = num.substring(0)
      }
      return parseFloat(num).toFixed(decimal)
    },
    //去申请页面
    goApplyBatch() {
      // 售后商品选择存入缓存，来实现页面切换时会显 start
      let batchListStorage = []
      batchListStorage.push(this.defaultGoods)
      this.batchGoodsList.map((item) => {
        batchListStorage.push(item)
      })
      //改变数据结构 过滤出 货品id，选中状态，当前数量
      let batchGoods = []
      batchListStorage.forEach((item) => {
        batchGoods.push({
          orderProductId: item.orderProductId,
          currNum: item.currNum,
          sel: item.sel
        })
      })
      // 售后商品选择存入缓存，来实现页面切换时会显 end

      let batchSelList = []
      batchSelList.push(this.defaultGoods)
      this.batchGoodsList.map((item) => {
        if (item.sel) {
          batchSelList.push(item)
        }
      })
      //多个商品
      let orderProductInfos = ''
      batchSelList.forEach((item) => {
        item.infopre = item.orderProductId + '-' + item.currNum
      })
      let Infos = []
      batchSelList.forEach((item) => {
        Infos.push(item.infopre)
      })
      //获取计算售后退款信息 计算结果为此次最多可退金额
      let param = {}
      param.url = 'v3/business/front/after/sale/apply/countReturnMoney'
      param.method = 'GET'
      param.data = {}
      param.data.orderSn = this.orderSn
      param.data.orderProductInfos = Infos.join(',') //退换的订单货品列表，格式为：id1-num1,id2-num2...num为空时表示此订单货品全部退换
      this.$request(param)
        .then((res) => {
          if (res.state == 200) {
            let result = res.data
            let pages = getCurrentPages()
            let prevPage = pages[pages.length - 2] //上一个页面
            prevPage.$vm.refundInfos = result
            prevPage.$vm.tosource = '1'
            prevPage.$vm.batchSelList = batchSelList
            prevPage.$vm.applyNum = result.number
            prevPage.$vm.returnAmount = result.maxReturnMoney
            prevPage.$vm.refundDetail.maxReturnMoney = result.maxReturnMoney
            prevPage.$vm.batchGoods = batchGoods
            this.$Router.back(1)
          } else {
            this.$api.msg(res.msg)
          }
        })
        .catch((e) => {
          //异常处理
        })
    }
  }
}
</script>

<style lang="scss">
page {
  background: $bg-color-split;
}

.batchSel{
	padding: 10rpx 20rpx;
	padding-right: 0;
	border-radius: 15rpx;
	background-color: #fff;
}

.default {
  box-sizing: border-box;
}

.batch_sel_list {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background: #ffffff;
}

// 商品的公共样式 每一个商品的样式
.sel_list_tag{
	&:last-child .right_con{
		  border-bottom: 0;
	}
}
.batch_sel_pre {
  box-sizing: border-box;
  display: flex;
  align-items: center;
 
  
  .right_con{
	  border-bottom: 1px solid #f2f2f2;
	  padding: 20rpx 0;
	  flex: 1;
	  margin-left: 22rpx;
  }
  
  .iconziyuan43{
	  color: #999;
  }
  
  .iconziyuan33{
  	  color: var(--color_main);
  }

  .sel_btn {
    width: 32rpx;
    height: 32rpx;
  }
  
  .num_unedit{
	  font-size: 24rpx;
	  font-family: PingFang SC;
	  font-weight: 500;
	  color: #999999;
  }

  .default_goods_image {
    width: 200rpx;
    height: 200rpx;
    background: #f3f3f3;
    border-radius: 14rpx;
    margin-right: 22rpx;

    image {
      width: 200rpx;
      height: 200rpx;
      border-radius: 14rpx;
    }
  }

  .default_goods_des {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 200rpx;

    .default_goods_name {
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #2D2D2D;
      width: 395rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .default_goods_spec {
      font-size: 26rpx;
      font-family: PingFang SC;
      font-weight: 400;
      color: #999;
      width: 395rpx;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
	  margin-top: 14rpx;
    }

    .default_goods_bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .default_goods_price {
        font-size: 24rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: var(--color_price);
        line-height: 30rpx;

        text:nth-child(2) {
          font-size: 34rpx;
        }
      }

      .default_goods_num {
        display: flex;
        justify-content: flex-end;

        .default_goods_number {
          display: flex;
          align-items: center;

          text:nth-of-type(1) {
            width: 51rpx;
            height: 50rpx;
            text-align: center;
            font-size: 26rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #949494;
            line-height: 46rpx;
            border: 1rpx solid #ddd;
			border-radius: 6rpx 0 0 6rpx;
          }

          .pre_num {
            font-size: 24rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #2e2e2e;
            width: 78rpx;
            height: 50rpx;
            line-height: 50rpx;
            border-top: 1rpx solid #ddd;
            border-bottom: 1rpx solid #ddd;
            text-align: center;
          }

          text:nth-of-type(2) {
            width: 51rpx;
            height: 50rpx;
            text-align: center;
            font-size: 26rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #2e2e2e;
            line-height: 46rpx;
            border: 1rpx solid #ddd;
			border-radius:  0 6rpx 6rpx 0;
          }
        }
      }
    }
  }
}

.batch_bottom {
  // width: 100%;
  height: 100rpx;
  background: #ffffff;
  box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(154, 154, 154, 0.1);
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;
  width: 750rpx;

  .submit_btn {
	width: 690rpx;
	height: 70rpx;
	border-radius: 35rpx;
    background: var(--color_main_bg);
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #ffffff;
    text-align: center;
    line-height: 70rpx;
	margin: 0 auto;
  }
}
</style>
